<template>
  <base-panel :show="visible" :width="panelWidth" @close="hide()" :re="true">
    <h3 slot="title">
      <span>{{$t('report.customReportAggregate.title5')}}</span>
      <el-dropdown
        class="pull-right"
        trigger="click"
        @command="setAdvanceSearchColumn"
      >
        <i
          class="iconfont icon-xitongguanli customer-panel-btn"
          style="float: none;"
        ></i>

        <el-dropdown-menu slot="dropdown" class="customer-advance-setting">
          <el-dropdown-item command="1">{{$t('common.base.table.oneCl')}}</el-dropdown-item>
          <el-dropdown-item command="2">{{$t('common.base.table.twoCl')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </h3>
    <div class="task-search-panel-title">
      <!-- 工单 -->
      <task-inquire :search-list="searchList" :column-num="columnNum" ref="taskInquire" v-if="reportType === 'task' || chartSatet === 1" :task-from="taskFrom" />
      <!-- 服务台 -->
      <!-- <search-form :search-list="searchList" :column-num="columnNum" ref="searchForm" v-else-if="reportType === 'event'" /> -->
      <!-- 客户 and 产品 -->
      <client-search-form :fields="fields" :column-num="columnNum" ref="clientSearchForm" v-if="['client', 'product', 3,4].includes(reportType !== 'produce' ? reportType : chartSatet)" :task-from="taskFrom" />
      <custom-app-search-form :fields="fields" :column-num="columnNum" ref="customSearchForm" v-if="['custom', 5].includes(reportType !== 'produce' ? reportType : chartSatet)" :task-from="taskFrom" />
    </div>
    <slot name="footer"></slot>
  </base-panel>
</template>
<script>
import { t } from '@src/locales';
import _ from 'lodash';
import { formatDate, formatAddress } from 'pub-bbx-utils';
import { isEmptyStringObject } from '@src/util/function';
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';

/* constants */
import {
  AllotTypeConvertMap,
  FlagConvertMap,
  TaskOnceConvertMap,
  TaskApproveConvertMap,
} from '@src/modules/task/model/TaskConvertMap.ts';
/* service */
import { convertFormQualityInfoFieldValueToQualityInfoRemoteData } from '@service/QualityInfoService.ts'
import { filterProductSearchParamsInvalidProperty } from '@service/ProductService.ts'
// component
import TaskInquire from './taskInquire'
import SearchForm from './searchForm'
import ClientSearchForm from './clientSearchForm'
import CustomAppSearchForm from './CustomAppSearchForm'

import {SELFFIELDS} from '../searchData'

import { stystemFields, SystemFieldNameEnum } from './PaaSAdvPanel/constant'

import { baseDistValueToObject, searchAddressObjectParams } from '@src/util/addressUtil';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();
const MultiFieldNames = [
  'serviceType',
  'serviceContent',
  'level',
  'paymentMethod',
  'state',
  'allotTypeStr',
  'onceException',
  'paymentMethod',
  'tag',
];
const TaskInquireConvertFieldNamesToConditionsMap = {
  customer: 'customerId',
  product: 'productId',
  tlmName: 'tlmId',
};
export default {
  name: 'task-search-panel',
  props: {
    searchList: {
      type: Array, // 搜索数据
      default: () => {[]}
    },
    reportType: {
      type: String, // 报表类型
      default: ''
    },
    chartSatet: {
      type: Number | String
    }, // 报表类型
    taskFrom: {
      type: Object | String
    }, // 初始值
  },
  data() {
    return {
      visible: false, // 弹框显示
      columnNum: 1, // 一栏还是两栏
      selfFields: this.buildSelfFields()
    }
  },
  computed: {
    fields() {
      let f = {};
      // 产品
      if (this.reportType === 'product' || this.chartSatet === 3) {
        let fields = [...this.searchList]
        return fields;
      }

      if(this.reportType === 'custom' || this.chartSatet === 5) {
     
        const systemFields = stystemFields.map(field => {
          return {
            ...field,
            fieldName: SystemFieldNameEnum[field.fieldName] || field.fieldName
          };
        }).filter(field => field.isSearch);
        return [...this.searchList, ...systemFields]
        
      }
      // 客户
      return [...this.searchList, ...SELFFIELDS]
        .filter(f => (f.isSearch || f.isSystem)
          && f.formType !== 'separator'
          && f.fieldName !== 'name'
          && f.fieldName !== 'lmPhone'
          && f.fieldName !== 'customerAddress'
          && f.fieldName !== 'lmName')
        .map(field => {
          f = _.cloneDeep(field);

          let formType = f.formType;

          if (formType === 'datetime') {
            formType = 'date';
          }

          if (f.fieldName === 'customer') {
            formType = 'customer'
          }

          if (f.fieldName === 'manager') {
            f.fieldName = 'customerManager';
          }

          if (f.displayName === this.$t('common.label.serviceTeam')) {
            formType = 'tags';
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
            orderId: f.isSystem ? f.orderId - 100 : f.orderId,
            operator: this.matchOperator(f),
          })
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    // 弹框宽度
    panelWidth() {
      return `${420 * this.columnNum}px`;
    }
  },
  methods: {
    // 一栏还是两栏
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // 显示
    show() {
      this.visible = true
    },
    // 隐藏
    hide() {
      this.visible = false
    },

    // 重置客户条件
    clientCreate() {
      if (this.reportType === 'task' || this.chartSatet === 1) {} 
      else if (this.reportType === 'event') {}
      else {
        this.$refs.clientSearchForm?.create()
      }
    },

    // 选中值
    buildParams() {
      let form, params, data, dataView;
      if (this.reportType === 'task' || this.chartSatet === 1) {
        form = this.$refs.taskInquire.returnData().data
        dataView = this.$refs.taskInquire.returnData().dataView
        data = this.$refs.taskInquire.fields

        const isSystemFields = data.filter((f) => f.isSystem);
        const notSystemFields = data.filter((f) => !f.isSystem);
        params = {systemConditions: [], conditions: []}
      
        let tv = null;
        let fn = '';
      
        // 固定条件
        for (let i = 0; i < isSystemFields.length; i++) {
          tv = isSystemFields[i];
          fn = tv.fieldName;
          const valueKey = Array.isArray(form[fn]) ? 'inValue' : 'value';

          if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) continue

          // 空对象
          if (typeof form[fn] === 'object' && !Array.isArray(form[fn]) && !Object.keys(form[fn]).length) continue 

          if (tv.formType === 'address') {
            let address = [];
            let isEmpty = isEmptyStringObject(form[fn]);

            if (!isEmpty) {
              if (form[fn].country){
                address.push({
                  property: 'country',
                  operator: tv.operatorValue,
                  value: form[fn].country,
                });
              }
              if (form[fn].province) {
                address.push({
                  property: 'province',
                  operator: tv.operatorValue,
                  value: form[fn].province,
                });
              }
              if (form[fn].city) {
                address.push({
                  property: 'city',
                  operator: tv.operatorValue,
                  value: form[fn].city,
                });
              }
              if (form[fn].dist) {
                address.push({
                  property: 'dist',
                  operator: tv.operatorValue,
                  value: form[fn].dist,
                });
              }
            }
            params.systemConditions = [...params.systemConditions, ...address];
            continue;
          }

          if (tv.fieldName == 'tags') {
            let condition = {
              property: 'tagIds',
              operator: tv.operatorValue,
              inValue: form[fn].map(({ id }) => id)
            };
            params.systemConditions.push(condition);
            continue;
          }

          if (tv.fieldName == 'state') {
            let condition = {
              property: fn,
              operator: tv.operatorValue,
              inValue: form[fn].map((stateName) =>
                TaskStateEnum.getValue(stateName)
              ),
            };
            params.systemConditions.push(condition);
            continue;
          }

          if (tv.fieldName === 'exceptionType') {
            let exceptionType;
            switch (form[fn]) {
            case this.$t('common.base.usualStatus.paused'):
              exceptionType = 1;
              break;
            case this.$t('common.base.usualStatus.overtime'):
              exceptionType = 2;
              break;
            default:
              exceptionType = 0;
              break;
            }
            params.systemConditions.push({
              property: 'exceptionType',
              operator: tv.operatorValue,
              value: exceptionType,
            });
            continue;
          }

          if (tv.fieldName == 'product') {
            params.systemConditions.push({
              property: 'productId',
              operator: tv.operatorValue,
              value: form[fn],
            });
            continue;
          }

          if (tv.fieldName === 'paymentMethod') {
            params.conditions.push({
              property: fn,
              operator: tv.operatorValue,
              inValue: form[fn],
            });
            continue;
          }

          if (tv.fieldName == 'allotTypeStr') {
            params.systemConditions.push({
              property: 'allotType',
              operator: tv.operatorValue,
              inValue: form[fn].map((type) => AllotTypeConvertMap[type]),
            });
            continue;
          }

          if (tv.fieldName == 'onceException') {
            params.systemConditions.push({
              property: 'flags',
              operator: tv.operatorValue,
              inValue: form[fn].map(
                (exception) => FlagConvertMap[exception] || ''
              ),
            });
            continue;
          }

          if (tv.fieldName === 'synergyId') {
            let condition = {
              property: 'synergies',
              operator: tv.operatorValue,
              inValue: form[fn],
            };
            params.systemConditions.push(condition);
            continue;
          }

          if (['date', 'datetime'].includes(tv.formType)) {
            params.systemConditions.push({
              property: fn,
              operator: tv.operatorValue,
              betweenValue1: form[fn][0],
              betweenValue2: form[fn][1],
            });
            continue;
          }

          if (tv.fieldName === 'executor') {
            params.systemConditions.push({
              property: 'executorUser',
              operator: tv.operatorValue,
              inValue: form[fn],
            });
            continue;
          }

          if (
            MultiFieldNames.indexOf(tv.formType) !== -1
          || tv.formType === 'user'
          ) {
            params.systemConditions.push({
              property: fn,
              operator: tv.operatorValue,
              inValue: form[fn],
            });
            continue;
          }

          if (TaskInquireConvertFieldNamesToConditionsMap[fn]) {
            params.systemConditions.push({
              property: TaskInquireConvertFieldNamesToConditionsMap[fn],
              operator: tv.operatorValue,
              value: form[fn],
            });
            continue;
          }

          let value = TaskOnceConvertMap[form[fn]] != undefined
            ? TaskOnceConvertMap[form[fn]]
            : form[fn];
          value = TaskApproveConvertMap[value] != undefined
            ? TaskApproveConvertMap[value]
            : value;

          params.systemConditions.push({
            property: fn,
            operator: tv.operatorValue,
            [valueKey]: form[fn],
          });
        }

        // 自定义条件
        for (let i = 0; i < notSystemFields.length; i++) {
          tv = notSystemFields[i];
          fn = tv.fieldName;
          // !tv.operator ? (tv['operator'] = this.matchOperator(tv)) : '';
          const valueKey = Array.isArray(form[fn]) ? 'inValue' : 'value';
          if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
            continue;
          }

          // 空对象
          if (
            typeof form[fn] === 'object'
          && !Array.isArray(form[fn])
          && !Object.keys(form[fn]).length
          ) {
            continue;
          }

          if (['date', 'datetime'].includes(tv.originalFormType)) {
            params.conditions.push({
              property: fn,
              operator: tv.operatorValue,
              betweenValue1: form[fn][0],
              betweenValue2: form[fn][1],
            });
            continue;
          }

          if (tv.formType === 'cascader') {
            params.conditions.push({
              property: fn,
              operator: tv.operatorValue,
              inValue: form[fn],
            });
            continue;
          }
          if (tv.formType === 'user' && Array.isArray(form[fn])) {
            params.conditions.push({
              property: fn,
              operator: 'user',
              inValue: form[fn],
            });
            continue;
          }

          if (tv.formType === 'select' && tv.setting.isMulti && !tv.isSystem) {
            params.conditions.push({
              property: fn,
              operator: tv.operatorValue,
              [valueKey]: form[fn],
            });
            continue;
          }

          params.conditions.push({
            property: fn,
            operator: tv.operatorValue,
            [valueKey]: form[fn],
          });
        }
      } 
      else if (this.reportType === 'event' || this.chartSatet === 2) {
        form = this.$refs.searchForm.returnData().data
        dataView = {}
      } else if(this.reportType === 'custom' || this.chartSatet === 5) {
        params = this.$refs.customSearchForm.buildParams()
        dataView = this.$refs.customSearchForm.buildParams()
      } else if(this.reportType === 'product' ||  this.chartSatet === 3) {
           params = {
            conditions: []
           }
            try {
              form = this.$refs.clientSearchForm.returnData()?.data ?? {};
            } catch (error) {
              console.warn(error, "error try catch");
            }

            dataView = this.$refs.clientSearchForm.returnData().dataView
            this.formBackup = Object.assign({}, form);

            const isSystemFields = this.fields.filter((f) => f.isSystem);
            const notSystemFields = this.fields.filter((f) => !f.isSystem);

            let tv = null;
            let fn = "";

            for (let i = 0; i < isSystemFields.length; i++) {
              tv = isSystemFields[i];
              fn = tv.fieldName;

              // hasRemind
              if (fn === "hasRemind" && form[fn] !== "") {
                params.hasRemind = form[fn] == 2 ? 0 : form[fn];
                continue;
              }

              if (fn === "qrcodeState" && form[fn] !== "") {
                params.qrcodeState = form[fn] == 2 ? 0 : form[fn];
                continue;
              }

              if (fn == "area") {
                // 国际化地址组件返回的第一个是国家，非国际化组件第一个返回的是省
                const address = baseDistValueToObject(form[fn])

                params.productAddress = {
                  ...(params.productAddress || {}),
                  ...(searchAddressObjectParams(address))
                };

                continue;
              }
              

              if (fn === "addressDetail") {
                params.productAddress = {
                  ...(params.productAddress || {}),
                  address: form[fn],
                };
                continue;
              }

              if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
                continue;
              }

              if (tv.formType === "date" || tv.formType === "datetime") {
                params[`${fn}Start`] = form[fn][0];
                params[`${fn}End`] = form[fn][1];
                continue;
              }

              if (tv.formType === "tags") {
                params.searchTagId = form[fn].map(({ id }) => id).join("");
              }

              if (typeof form[fn] === "string") {
                params[fn === "customer" ? "customerId" : fn] = form[fn];
                continue;
              }

              if (typeof form[fn] === "number") {
                params[fn] = form[fn];
                continue;
              }
            }

            for (let i = 0; i < notSystemFields.length; i++) {
              let key = null;
              tv = notSystemFields[i];
              fn = tv.fieldName;

              if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
                continue;
              }

              // 空对象
              if (
                typeof form[fn] === "object"
                && !Array.isArray(form[fn])
                && !Object.keys(form[fn]).length
              ) {
                continue;
              }

              if (tv.originalFormType === "date") {
                params.conditions.push({
                  property: fn,
                  operator: tv.operator,
                  betweenValue1: formatDate(form[fn][0], "YYYY-MM-DD"),
                  betweenValue2: formatDate(form[fn][1], "YYYY-MM-DD"),
                });
                continue;
              }

              if (tv.originalFormType === "datetime") {
                params.conditions.push({
                  property: fn,
                  operator: tv.operator,
                  betweenValue1: formatDate(form[fn][0], "YYYY-MM-DD HH:mm:ss"),
                  betweenValue2: `${formatDate(form[fn][1], "YYYY-MM-DD")} 23:59:59`,
                });
                continue;
              }

              if (tv.formType === "cascader") {
                params.conditions.push({
                  property: fn,
                  operator: tv.operator,
                  inValue: form[fn],
                });
                continue;
              }

              if (tv.formType === "address") {
                let address = {
                  property: fn,
                  operator: tv.operator,
                };
                let isEmpty = isEmptyStringObject(form[fn]);

                if (!isEmpty) {
                  address.value = formatAddress(form[fn],'')
                }
                params.conditions.push(address);
                continue;
              }

              // 非国际化地址高级搜索需要去掉中国
              if (tv.formType == 'area' && !internationalGray && form[fn] && form[fn][0] == '中国') {
                const value = form[fn].filter((item, index) => index != 0)
                params.conditions.push({
                  property: fn,
                  operator: tv.operator,
                  value,
                })
                continue
              }

              if (tv.originalFormType === "related_task") {
                key = "taskNo";
              }

              params.conditions.push({
                property: fn,
                operator: tv.operator,
                value: form[fn],
                key,
              });
            }

       
            // 质保信息数据处理
            params = Object.assign(params, convertFormQualityInfoFieldValueToQualityInfoRemoteData(params))
            // const qualitySearchParams = buildQualityInfoSearchParams(params)
            const allParams = Object.assign(params)
            
            params = filterProductSearchParamsInvalidProperty(allParams)
      }
      else {
        form = this.$refs.clientSearchForm.returnData().data
        dataView = this.$refs.clientSearchForm.returnData().dataView

        const isSystemFields = this.fields.filter(f => f.isSystem);
        const notSystemFields = this.fields.filter(f => !f.isSystem);
        params = {
          conditions: [],
        };

        let tv = null;
        let fn = '';
        for(let i = 0;i < isSystemFields.length;i++) {
          tv = isSystemFields[i];
          fn = tv.fieldName;

          // hasRemind
          if ((fn === 'hasRemind' || fn === 'status') && form[fn] !== '') {
            params[fn] = form[fn];
            continue;
          }

          if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
            continue;
          }

          if (fn === 'area') {
            
            // 国际化地址组件返回的第一个是国家，非国际化组件第一个返回的是省
            let {country, province, city, dist} = baseDistValueToObject(form[fn])
            params.customerAddress = {
              ...params.customerAddress || {},
              adProvince: province,
              adCity: city,
              adDist: dist
            }
            country && (params.customerAddress.adCountry = country);
            continue;
          }

          if (fn === 'addressDetail') {
            params.customerAddress = {
              ...params.customerAddress || {},
              adAddress: form[fn]
            }
            continue;
          }

          if(['date', 'datetime'].includes(tv.formType)) {
            params[`${fn}Start`] = form[fn][0];
            params[`${fn}End`] = form[fn][1];
            continue;
          }

          if (tv.formType === 'tags') {
            params.tagId = form[fn].map(({id}) => id).join('');
          }

          if (typeof form[fn] === 'string') {
            params[fn === 'customer' ? 'customerId' : fn] = form[fn];
            continue;
          }

          params[fn] = form[fn];
        }

        for(let i = 0;i < notSystemFields.length;i++) {
          let key = null;
          tv = notSystemFields[i];
          fn = tv.fieldName;

          if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
            continue;
          }

          // 空对象
          if (typeof form[fn] === 'object' && !Array.isArray(form[fn]) && !Object.keys(form[fn]).length) {
            continue;
          }

          if (['date', 'datetime'].includes(tv.originalFormType)) {
            params.conditions.push({
              property: fn,
              operator: tv.operator,
              betweenValue1: form[fn][0],
              betweenValue2: form[fn][1],
            });
            continue;
          }

          if (tv.formType === 'cascader') {
            params.conditions.push({
              property: fn,
              operator: tv.operator,
              inValue: form[fn]
            });
            continue;
          }

          if (tv.formType === 'address') {
            let address = {
              property: fn,
              operator: tv.operator,
            };
            let isEmpty = isEmptyStringObject(form[fn]);

            if(!isEmpty) {
              address.value = formatAddress(form[fn],'')
              params.conditions.push(address);
            }
            continue;
          }

          if (tv.originalFormType === 'related_task') {
            key = 'taskNo';
          }


          params.conditions.push({
            property: fn,
            operator: tv.operator,
            value: form[fn],
            key
          });
        }
      }
    
      return {params, dataView}
    },

    // 初始化操作符
    matchOperator(field) {
      let formType = field.formType;
      let operator = '';

      switch (formType) {
      case 'date': {
        operator = 'between';
        break;
      }
      case 'datetime': {
        operator = 'between';
        break;
      }
      case 'select': {
        if(field.setting && field.setting.isMulti) {
          operator = 'contain';
        } else {
          operator = 'eq';
        }
        break;
      }
      case 'cascader': {
        operator = 'cascader';
        break;
      }
      case 'user': {
        operator = 'user';
        break;
      }
      case 'address': {
        operator = 'address';
        break;
      }
      case 'location': {
        operator = 'location';
        break;
      }
      case 'related_task': {
        operator = 'array_eq';
        break;
      }
      case 'formula': {
        operator = 'eq';
        break;
      }
      default: {
        operator = 'like';
        break;
      }
      }
      return operator;
    },

    // 产品参数
    buildSelfFields() {
      let fields = [
        {
          displayName: t('common.base.createTime'),
          fieldName: 'createTime',
          formType: 'datetime',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          operator: 'between',
          orderId: -2
        },
        {
          displayName: t('common.label.hasRemind'),
          fieldName: 'hasRemind',
          formType: 'select',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          operator: 'between',
          orderId: -3,
          setting: {
            isMulti: false,
            dataSource: [
              {
                text: t('common.base.all'),
                value: ''
              },
              {
                text: t('common.base.hasState.0'),
                value: 1
              },
              {
                text: t('common.base.hasState.1'),
                value: 2
              }
            ]
          }
        },
        {
          displayName: t('common.base.createUser'),
          fieldName: 'createUser',
          formType: 'user',
          returnData: 'name',
          noClearable: true,
          isExport: false,
          isNull: 1,
          isSystem: 1,
          orderId: -3.5,
          placeHolder: t('product.placeholder.createUser')
        }, {
          displayName: t('product.type.qrcodeState'),
          fieldName: 'qrcodeState',
          formType: 'select',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          operator: 'between',
          orderId: 1000,
          setting: {
            isMulti: false,
            dataSource: [
              {
                text: t('common.base.all'),
                value: ''
              },
              {
                text: t('common.base.yes'),
                value: 1
              },
              {
                text: t('common.base.no'),
                value: 2
              }
            ]
          }
        }
      ];

      let hasLinkman = this.searchList.filter(
        item => item.fieldName == 'linkmanName'
      )[0];
      let hasAddress = this.searchList.filter(
        item => item.fieldName == 'address'
      )[0];

      if (hasLinkman) {
        fields.push({
          displayName: this.$t('product.detail.catalogView.type.linkman'),
          fieldName: 'linkmanId',
          formType: 'linkman',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          orderId: -11,
          placeholder: this.$t('common.form.placeHolder.linkman.pla1')
        });
      }

      if (hasAddress) {
        fields.push({
          displayName: this.$t('common.base.locationMap.area'),
          fieldName: 'area',
          formType: 'area',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          orderId: -10
        });
        fields.push({
          displayName: this.$t('common.base.locationMap.detail'),
          fieldName: 'addressDetail',
          formType: 'text',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          orderId: -9
        });
      }

      return fields;
    },

    resetFormValue() {
      this.$refs?.customSearchForm?.initFormVal()
    },
  },
  components: {
    [TaskInquire.name]: TaskInquire,
    [SearchForm.name]: SearchForm,
    [ClientSearchForm.name]: ClientSearchForm,
    [CustomAppSearchForm.name]: CustomAppSearchForm
  }
}
</script>
<style lang="scss" scoped>
.task-search-panel-title {
  padding: 0 15px;
  overflow: hidden;
  overflow-y: scroll;
  height: 600px;
  padding-bottom: 200px;
}
</style>